<?php
class Category
{    
    private $db;
	
    /***
     * 构造函数
     */
    function __construct($db) {
        $this->db = $db;
    }

	function child_add($id,$num)//id:当前id; num:需要操作的字符
	{
		$sql = 'select parent_id from categories where id='.$id.' limit 1';
		$data = $this->db->query($sql)->getOne();
		
		$category_sql = 'select id,parent_id,child_id from categories where id='.$data['parent_id'].' limit 1';
		$rs = $this->db->query($category_sql)->getOne();
		
		$child_string = '';
		
		if($rs['child_id']==''){
			$child_string .= $num;
		}else{
			$child_array = explode(',',$rs['child_id']);
			array_push($child_array,$num);
			$child_array = array_unique($child_array);//去重复
			sort($child_array,SORT_NUMERIC);
			$child_string = implode(',',$child_array);
		}
		
		$data = array('child_id'=>($child_string));
		$this->db->table('categories')->where('id = '.$rs['id'])->update($data)->run();
		
		if($rs['parent_id']!=0){
			$this->child_add($rs['id'],$num);
		}
	}
	
	function child_del($id,$num)//id:当前id; num:需要操作的字符
	{
		$sql = 'select parent_id,child_id from categories where id='.$id.' limit 1';
		$data = $this->db->query($sql)->getOne();
		
		$category_sql = 'select id,parent_id,child_id from categories where id='.$data['parent_id'].' limit 1';
		$rs = $this->db->query($category_sql)->getOne();
		
		if($rs['child_id']==''){
			return false;
		}else{
			$child_array = explode(',',$rs['child_id']);
			unset($child_array[array_search($num, $child_array)]);//先查操作的字符num的下标，再注销数组当前下标的元素
			sort($child_array,SORT_NUMERIC);
			$child_string = implode(',',$child_array);
		}
		
		$data = array('child_id'=>($child_string));
		$this->db->table('categories')->where('id = '.$rs['id'])->update($data)->run();
		
		if($rs['parent_id']!=0){
			$this->child_del($rs['id'],$num);
		}
		
		return true;
	}
	
}